<template>
  <section>
    <el-container>
      <el-header>
        <bread-crumb :model-value="navData"></bread-crumb>
      </el-header>
      <el-container>
        <el-aside width="300px">
          <chapter-tree :course-id="params.courseId" @show="handleShow" ref="chapterTreeRef"></chapter-tree>
        </el-aside>
        <el-main>
          <keep-alive>
            <component :is="getComponent" :rowData="rowData" @submit="handleSubmit"></component>
          </keep-alive>
        </el-main>
      </el-container>
    </el-container>
  </section>
</template>
<script setup lang="ts">
import { defineProps, reactive, ref, computed, h, onDeactivated } from "vue";
import ChapterTree from "@/components/chapter/ChapterTree.vue";
import InsertComponent from "@/components/chapter/ChapterInsert.vue";
import InsertRootComponent from "@/components/chapter/ChapterInsertRoot.vue";
import UpdateComponent from "@/components/chapter/ChapterUpdate.vue";
import UpdateRootComponent from "@/components/chapter/ChapterUpdateRoot.vue";
import BreadCrumb from "@/components/public/BreadCrumb.vue";

// 要修改的行数据
const rowData = ref<any>({});


// 声明父传子数据的高级用法：约定传入的参数类型
type Params = {
  params: {
    courseName: string,
    courseId: number,
  }
}

const props = defineProps<Params>();

const showValue = ref<string>("");

// 面包屑数据
const navData = reactive([
  {
    name: "课程列表",
    to: "/home/course"
  },
  {
    name: "章节管理"
  },
  {
    name: props.params.courseName
  }
]);

/**
 * 显示组件
 * @param 
 */
const handleShow = (value: string, row?: any) => {
  showValue.value = value;
  if (row) {
    // 增加时只需要传入course_id,parent_id,sort其余字段不需要
    if (showValue.value == "insert") {
      rowData.value = {
        course_id: props.params.courseId,
        sort: row.sort,
        // 父节点：如果是根节点parent_id和parent_name为null
        parent_id: row.id,
        parent_name: row.name
      }
      return;
    }
    rowData.value = row;
  }
}


// 根据showValue返回不同的组件
const getComponent = computed(() => {
  if (showValue.value == "insertRoot") {
    return InsertRootComponent;
  } else if (showValue.value == "insert") {
    return InsertComponent;
  } else if (showValue.value == "update") {
    return UpdateComponent;
  } else if (showValue.value == "updateRoot") {
    return UpdateRootComponent;
  } else {
    return h("div", "章节管理");
  }
});

const chapterTreeRef = ref<any>();

/**
 * 关闭组件，判断是否增加或修改了数据，以更新数据
 * @param updateData 
 */
const handleSubmit = (action: 'insert' | 'update', updateData: any) => {
  if (updateData) {
    console.log("updateData",updateData);
    if (action == "insert") {
      chapterTreeRef.value.appendNode(updateData);
    } else {
      chapterTreeRef.value.updateNode(updateData);
      showValue.value = "";
    }
  }
}

// 组件失活后，重置showValue的值，避免缓存导致页面显示错误
onDeactivated(() => {
  showValue.value = "";
});

</script>
<style lang="scss" scoped></style>